package jun.home.dailycost.validator;

import jun.home.dailycost.domain.Category;
import jun.home.dailycost.domain.Item;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

@Component("itemValidator")
public class ItemValidator implements Validator {

	// TODO: check if this is valid CategoryValidator
	// e.g. if catValidator.support(Category.clazz) is true
	@Autowired
	private CategoryValidator categoryValidator;

	@Override
	public boolean supports(Class<?> clazz) {
		return Item.class.equals(clazz);
	}

	@Override
	public void validate(Object obj, Errors e) {
		ValidationUtils.rejectIfEmptyOrWhitespace(e, "cost", "field.empty");
		ValidationUtils.rejectIfEmptyOrWhitespace(e, "remark", "field.empty");
		ValidationUtils.rejectIfEmpty(e, "date", "field.empty");
//		ValidationUtils.rejectIfEmpty(e, "cat", "field.empty");
		Item item = (Item) obj;
		if (item.getCost() <= 0) {
			e.rejectValue("cost", "cost.invalid.range");
		}
		if (item.getRemark().length() >= 500) {
			e.rejectValue("remark", "remark.invalid.length");
		}
		Category cat = item.getCat();
		if (cat != null) {
			try {
				e.pushNestedPath("cat");
				ValidationUtils.invokeValidator(categoryValidator, cat, e);
			} finally {
				e.popNestedPath();
			}
		} else {
			e.rejectValue("cat", "field.empty");
		}
	}

}
